<template>
  <a-modal
    :visible="visible"
    title-align="start"
    :ok-text="$t('modal.operation.save')"
    :cancel-text="$t('modal.operation.cancel')"
    unmount-on-close
    @before-ok="handleSave"
    @close="handleClose"
    @cancel="handleCancel"
  >
    <template #title
      >{{
        saveId
          ? $t('searchTable.operation.edit')
          : $t('searchTable.operation.create')
      }}
    </template>
    <a-form ref="formRef" :rules="rules" :model="formData" auto-label-width>
      <a-form-item field="title" label="标题">
        <a-input
          v-model="formData.title"
          allow-clear
          placeholder="请输入标题"
        ></a-input>
      </a-form-item>
      <a-form-item field="content" label="内容">
        <a-textarea
          v-model="formData.content"
          placeholder="请输入内容"
          :auto-size="{ minRows: 3, maxRows: 5 }"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import {
    createAnnouncement,
    editAnnouncement,
    getAnnouncementDetail,
  } from '@/api/announcement';
  import { AnnouncementRecord } from '@/api/announcement/types';

  const emit = defineEmits(['saveSuccess']);

  const formRef = ref();
  const formData = ref<AnnouncementRecord>({
    id: undefined,
    title: '',
    content: '',
  });
  const visible = ref(false);
  const saveId = ref();
  const rules = {
    title: [{ required: true, message: '请输入标题' }],
    content: [{ required: true, message: '请输入描述' }],
  };

  const handleSave = async () => {
    try {
      const isInvalid = await formRef.value?.validate();
      if (isInvalid) return false;
      // 保存和编辑
      if (saveId.value) {
        await editAnnouncement(formData.value);
      } else {
        await createAnnouncement(formData.value);
      }
      visible.value = false;
      Message.success('保存成功');
      emit('saveSuccess');
      return true;
    } catch (error) {
      return false;
    }
  };
  // 编辑
  const handleEdit = async (id: number) => {
    saveId.value = id;
    const result = await getAnnouncementDetail(id);
    formData.value = result.data;
    visible.value = true;
  };
  const handleOpen = () => {
    visible.value = true;
  };
  const handleCancel = () => {
    visible.value = false;
  };
  // 对话框关闭后触发
  const handleClose = () => {
    formData.value.title = '';
    formData.value.content = '';
    formData.value.id = undefined;
    saveId.value = undefined;
  };
  defineExpose({
    handleOpen,
    handleEdit,
  });
</script>

<style scoped lang="less"></style>
